package cn.xz.kjg.activity

import android.content.ContentValues.TAG
import android.util.DisplayMetrics
import android.util.Log
import cn.xz.kjg.R
import cn.xz.kjg.base.BaseActivity
import cn.xz.kjg.bean.*
import cn.xz.kjg.databinding.ActivityLoadingBinding
import cn.xz.kjg.dialog.ProgressDialog
import cn.xz.kjg.net.OkHttpUtil
import cn.xz.kjg.net.OkhttpResponseHandle
import cn.xz.kjg.util.AppHelper
import cn.xz.kjg.util.SessionUtils
import cn.xz.kjg.util.gone
import cn.xz.kjg.util.visible
import okhttp3.Request
import java.text.DateFormat
import java.text.SimpleDateFormat
import kotlin.math.sqrt

/**
 * 下载配置界面*/
class LoadingActivity: BaseActivity<ActivityLoadingBinding>(R.layout.activity_loading) {

    //当前下载进度
    private var downNum = 0
    //总下载数量
    private val allDownNum = 5
    //是否有下载失败的
    private var downError = false

    override fun initData() {
        //获取设备基本信息
        getScreenHW()
        //下载的进度条默认五个
        mDataBind.downloadProgressbar.max = allDownNum
    }

    override fun initEvent() {
        //返回
        mDataBind.tvBack.setOnClickListener {
            finish()
        }
        //下载
        mDataBind.ivDown.setOnClickListener {
            getAPPData()
        }
        //点击下载完成
        mDataBind.btnFinish.setOnClickListener {
            mDataBind.clFinishDown.gone()
            mDataBind.tvUpError.gone()
            downError = false
        }
        mDataBind.clFinishDown.setOnClickListener {  }
    }

    private fun getAPPData(){
        //开始下载
        mDataBind.tvDwnNum.text = "0/$allDownNum"
        mDataBind.tvDwnNum.visible()
        mDataBind.downloadProgressbar.visible()
        //显示加载框
        showLoading(true)
        var i = 1
        //获取灯光列表
        getLight(object :DownListener{
            override fun onSuccess() {
                upDataSeekBar(i++)
            }
            override fun onFailure() {
                downError = true
                upDataSeekBar(i++)
            }
        })
        //获取设备列表
        android.os.Handler().postDelayed({
            getDevice(object :DownListener{
                override fun onSuccess() {
                    upDataSeekBar(i++)
                }
                override fun onFailure() {
                    downError = true
                    upDataSeekBar(i++)
                }
            })
        }, 1000)
        //获取展区列表
        android.os.Handler().postDelayed({
            getAreaList(object :DownListener{
                override fun onSuccess() {
                    upDataSeekBar(i++)
                }
                override fun onFailure() {
                    downError = true
                    upDataSeekBar(i++)
                }
            })
        }, 2000)
        //获取其他设备
        android.os.Handler().postDelayed({
            getDHList(object :DownListener{
                override fun onSuccess() {
                    upDataSeekBar(i++)
                }
                override fun onFailure() {
                    downError = true
                    upDataSeekBar(i++)
                }
            })
        }, 3000)
        //获取登录信息
        android.os.Handler().postDelayed({
            getApp(object :DownListener{
                override fun onSuccess() {
                    upDataSeekBar(i++)
                }
                override fun onFailure() {
                    downError = true
                    upDataSeekBar(i++)
                }
            })
        }, 4000)
    }

    private fun getScreenHW() {
        val metric = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels // 屏幕宽度（像素）
        val height = metric.heightPixels // 屏幕高度（像素）
        val density = metric.density // 屏幕密度（0.75 / 1.0 / 1.5）
        val densityDpi = metric.densityDpi // 屏幕密度DPI（120 / 160 / 240）
        val diagonalPixels = sqrt(Math.pow(width.toDouble(), 2.0) + Math.pow(height.toDouble(), 2.0))
        val screenSize = diagonalPixels / (160 * density)
        mDataBind.tvCc.text = "宽:$width  高:$height  DPI:$densityDpi"
        mDataBind.tvV.text = "版本号:" + AppHelper.getAppVersionName()
        getLastTime()
    }

    //获取过期时间
    private fun getLastTime(){
        val dateLogin = SessionUtils.getObject<DateLogin>(CommonLib.Date_Login,DateLogin::class.java)
        if (dateLogin != null){
            val format: DateFormat = SimpleDateFormat("yyyy-MM-dd")
            val fwqTime = format.parse(dateLogin.date).time
            var s = "应用已过期"
            if (fwqTime > System.currentTimeMillis()) {
                val t: Int = ((fwqTime - System.currentTimeMillis().toLong()) / 86400000).toInt()
                s = "应用过期时间：" + t + "天"
            }
            mDataBind.tvTime.text = s
        }
    }

    private fun getLight(mListener: DownListener){
        OkHttpUtil.get(this@LoadingActivity,
            "http://ipad.cloud.plusbe.com/LightList.aspx?seviceID=${CommonLib.MY_APP_CODE}",
            LightLists::class.java, object : OkhttpResponseHandle<LightLists?>() {
                override fun onSuccess(response: LightLists?) {
                    if (response != null && response.list != null && response.list.isNotEmpty()){
                        //将灯光列表存储起来
                        SessionUtils.commitDataList(CommonLib.Light_CACHE,response.list)
                    }
                    mListener.onSuccess()
                }

                override fun onFailure(request: Request?, e: Exception?) {
                    super.onFailure(request, e)
                    mListener.onFailure()
                }
            })
    }

    private fun getDevice(mListener: DownListener){
        OkHttpUtil.get(this@LoadingActivity,
            "http://ipad.cloud.plusbe.com/DeviceList.aspx?seviceID=${CommonLib.MY_APP_CODE}&r=" + (Math.random() * 10000).toInt(),
            DeviceLists::class.java, object : OkhttpResponseHandle<DeviceLists?>() {
                override fun onSuccess(response: DeviceLists?) {
                    Log.e(TAG, "onSuccess: 1234->设备列表下载成功")
                    if (response != null && response.list != null && response.list.isNotEmpty()){
                        //将设备列表存储起来
                        SessionUtils.commitDataList(CommonLib.Device_CACHE,response.list)
                    }
                    mListener.onSuccess()
                }

                override fun onFailure(request: Request?, e: java.lang.Exception?) {
                    super.onFailure(request, e)
                    mListener.onFailure()
                }
            })
    }

    private fun getAreaList(mListener: DownListener){
        OkHttpUtil.get(this@LoadingActivity,
            "http://ipad.cloud.plusbe.com/areaList.aspx?seviceID=${CommonLib.MY_APP_CODE}",
            AreaLists::class.java, object : OkhttpResponseHandle<AreaLists?>() {
                override fun onSuccess(response: AreaLists?) {
                    if (response != null && response.list != null && response.list.isNotEmpty()){
                        //将展厅列表存储起来
                        SessionUtils.commitDataList(CommonLib.Hall_CACHE,response.list)
                    }
                    mListener.onSuccess()
                }

                override fun onFailure(request: Request?, e: java.lang.Exception?) {
                    super.onFailure(request, e)
                    mListener.onFailure()
                }
            })
    }

    private fun getDHList(mListener: DownListener){
        OkHttpUtil.get(this@LoadingActivity, "http://ipad.cloud.plusbe.com/dh_deviceList.aspx?seviceID=${CommonLib.MY_APP_CODE}", DeviceLists::class.java, object :
            OkhttpResponseHandle<DeviceLists?>() {
            override fun onSuccess(response: DeviceLists?) {
                if (response != null && response.list != null && response.list.isNotEmpty()){
                    //将其他设备存储起来
                    SessionUtils.commitDataList(CommonLib.DH_CACHE,response.list)
                }
                mListener.onSuccess()
            }

            override fun onFailure(request: Request?, e: java.lang.Exception?) {
                super.onFailure(request, e)
                mListener.onFailure()
            }
        })
    }

    private fun getApp(mListener: DownListener){
        OkHttpUtil.get(this@LoadingActivity,
            "http://ipad.cloud.plusbe.com/Datelogin.aspx?seviceID=${CommonLib.MY_APP_CODE}",
            DateLogin::class.java, object : OkhttpResponseHandle<DateLogin?>() {
                override fun onSuccess(response: DateLogin?) {
                    if (response != null){
                        //将设备列表存储起来
                        SessionUtils.commitObject(CommonLib.Date_Login,response)
                    }
                    mListener.onSuccess()
                }

                override fun onFailure(request: Request?, e: java.lang.Exception?) {
                    super.onFailure(request, e)
                    mListener.onFailure()
                }
            })
    }

    //下载进度更新
    private fun upDataSeekBar(i: Int){
        mDataBind.tvDwnNum.text = "$i/5"
        mDataBind.downloadProgressbar.progress  = i
        if (i == allDownNum){
            downFinish()
        }
    }

    //显示加载框，目的是在下载资源过程中禁止用户误操作
    var loadingD: ProgressDialog? = null
    private fun showLoading(b: Boolean){
        try {
            if (b){
                if (loadingD == null){
                    loadingD = ProgressDialog.newInstance()
                }
                loadingD?.show(this.supportFragmentManager, "ProgressDialog")
            }else{
                if (loadingD != null){
                    loadingD?.dismiss()
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    //虚拟键禁用
    override fun onBackPressed() {}

    //下载完成
    private fun downFinish(){
        downNum = 0 //进度条进度清零
        mDataBind.downloadProgressbar.progress = 0
        //隐藏进度条
        mDataBind.tvDwnNum.gone()
        //加载框隐藏
        showLoading(false)
        //获取过期时间
        getLastTime()
        mDataBind.downloadProgressbar.gone()
        mDataBind.clFinishDown.visible()
        if (downError){
            mDataBind.tvUpError.visible()
        }
    }

    //下载回调
    interface DownListener {
        fun onSuccess()
        fun onFailure()
    }
}